package it.polimi.traveldream.web.beans.login;

import it.polimi.traveldream.managers.credentials.UserCredentialManager;
import it.polimi.traveldream.persistence.dtos.UserDTO;

import java.io.IOException;
import java.security.Principal;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

@ManagedBean(name="redirectBean")
@ViewScoped
public class RedirectBean {

	@EJB
	private UserCredentialManager userMgr;

	public void redirect() throws IOException {
		FacesContext currentInstance = FacesContext.getCurrentInstance();
		//controlla che non si stia ricaricando la pagina a causa di un bottone o qualche evento all'interno della pagina stessa
		//serve ad impedire loop infiniti
		if(!currentInstance.isPostback()) {
			ExternalContext externalContext = currentInstance.getExternalContext();
			String baseURL = externalContext.getApplicationContextPath();
			Principal principal = externalContext.getUserPrincipal();
			if(principal != null) {
				System.out.print("Redirection: the principal is not null.");
				UserDTO user = userMgr.find(principal.getName());

				if(user.getIsClient()) {
					System.out.println(" Role: Cliente");
					externalContext.redirect(baseURL + "/cliente/index.xhtml");

				} else {
					System.out.println(" Role: Impiegato");
					externalContext.redirect(baseURL + "/impiegato/index.xhtml");
				}
			} else {
				System.out.println("Redirection: the principal is null");
			}
		}
	}
}
